<?php
declare(strict_types=1);

namespace Core\Listener;

use Dotenv\Dotenv;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Framework\Event\BootApplication;

#[Listener]
class MergeDockerEnv implements ListenerInterface
{
    public function listen(): array
    {
        // 返回一个该监听器要监听的事件数组，可以同时监听多个事件
        return [
            BootApplication::class,
        ];
    }

    public function process(object $event): void
    {
        $data = Dotenv::createMutable([BASE_PATH])->safeLoad();
        $new = [];
        foreach ($data as $key => $value) {
            $new[$key] = !empty(getenv($key)) ? getenv($key) : $value;
        }
        $content = implode("\n", array_map(function ($key, $value) {
            return "{$key}={$value}";
        }, array_keys($new), array_values($new)));
        file_put_contents(BASE_PATH . '/.env', $content);
        container()->get(StdoutLoggerInterface::class)->info('已将docker环境变量合并到.env文件');
    }
}